package com.example.chatroom.controller;

import com.example.chatroom.common.errorcode.ControllerErrorCodeConstants;
import com.example.chatroom.common.exception.ControllerException;
import com.example.chatroom.common.pojo.CommonResult;
import com.example.chatroom.controller.result.SessionListResult;
import com.example.chatroom.service.ISessionService;
import com.example.chatroom.service.dto.SessionListDTO;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/session")
public class SessionController {
    @Autowired
    private ISessionService sessionService;
    @GetMapping("/sessionList")
    public CommonResult<List<SessionListResult>> getSessionList(HttpServletRequest request){
        log.info("getSessionList()");
        return CommonResult.success(coverToSessionListResults(sessionService.getSessionList(request)));
    }

    private List<SessionListResult> coverToSessionListResults(List<SessionListDTO> sessionList) {
        if(sessionList==null){
            log.error(ControllerErrorCodeConstants.SESSION_GET_ERROR.getMsg());
            throw new ControllerException(ControllerErrorCodeConstants.SESSION_GET_ERROR);
        }
        return sessionList.stream().map(sessionListDTO -> {
            SessionListResult sessionListResult=new SessionListResult();
            sessionListResult.setSessionId(sessionListDTO.getId());
            sessionListResult.setFriends(sessionListDTO.getFriends());
            sessionListResult.setLastMessage(sessionListDTO.getLastMessage());
            return sessionListResult;
        }).collect(Collectors.toList());
    }

    @PostMapping("/add")
    public CommonResult<Long> addSession(@RequestParam(value = "toUserId",required = true)Long toUserId,
                                         HttpServletRequest request){
        log.info("addSession toUserId:{}",toUserId);
        Long sessionId=sessionService.addSession(toUserId,request.getHeader("user_token"));
        return CommonResult.success(sessionId);
    }

}
